// 生成验证码
function generateCode() {
    const randomStr = '00000' + Math.floor(Math.random() * 1000000)
    let code = randomStr.substring(randomStr.length - 6)
    return code
}

// 设置验证码
async function setVerifyCode(mobile, code, type) {
    let expiresIn = 5 * 60 * 1000
    let result = await uniCloud.callFunction({
        name: 'user-center',
        data: {
            action: 'setVerifyCode',
            params: {type, code: code, expiresIn, mobile: mobile}
        }
    })
    return result
}

//发送短信验证码
function sendSms(mobile, type = "register") {
    let code = generateCode()
    // 发送短信
    let result = uniCloud.callFunction({
        name: 'user-center',
        data: {
            action: 'sendSmsCode',
            params: {type, code: code, mobile: mobile, templateId: '10199'}
        }
    }).then(mobileRes => {
        console.log(mobileRes)
        // todo 这里需要添加发送成功和失败的判断，如果失败则不执行下面的方法
        return setVerifyCode(mobile, code, type)
    }).catch(err => {
        console.error(err)
        return err
    })
    return result
}

//验证码登陆
function loginBySms({action = 'loginBySms', mobile, code}) {
    let result = uniCloud.callFunction({
        name: 'user-center',
        data: {action, mobile, code}
    })
    return result
}

module.exports = {sendSms, loginBySms};
